package com.yhyvr.api.service.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lz.kit.LogKit;
import com.lz.kit.Prop;
import com.lz.kit.PropKit;
import com.lz.kit.ehcache.CacheKit;
import com.lz.mybatis.jdbc.auto.dao.WxTokenMapper;
import com.lz.mybatis.jdbc.auto.model.WxToken;
import com.lz.mybatis.jdbc.auto.model.WxTokenExample;
import com.lz.tool.ListUtils;
import com.lz.tool.OkHttpUtil;
import com.lz.tool.UUIDTool;
import com.tencent.common.Sign;
import com.yhyvr.constant.WxConstant;
import com.yhyvr.pojo.req.api.ApiReqData;
import com.yhyvr.pojo.req.api.wx.WxJsapiReq;
import com.yhyvr.pojo.resp.api.ApiRespData;
import com.yhyvr.pojo.resp.api.wx.WxJsapiResp;
import org.apache.commons.lang3.StringUtils;
import org.beetl.ext.fn.Json;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by - on 2016/11/17.
 * 微信相关服务
 */

@Service
public class WxService {
    /**
     * 获取accessToken 并缓存
     * @return
     */
    @Transactional
    public JSONObject getSnsParam(String code){
      Prop propKit = PropKit.use("three-app.properties");
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + propKit.get("wx.appid") + "&secret=" + propKit.get("wx.appsecret") + "&code=" + code + "&grant_type=authorization_code";
            String json = null;
          try {
                json = OkHttpUtil.get(url);
              System.out.println("获取openid"+json);
            JSONObject g = JSON.parseObject(json);
            return g;
          } catch (Exception e) {
              e.printStackTrace();
              return null;
        }

    }

    /**
     * 获取js accessToken 并缓存
     * @return
     */
    public String getJsApiAccessToken(){
        String accessToken = CacheKit.get(WxConstant.wxCache,WxConstant.jsapiAccessTokenCache);
       if(StringUtils.isNotBlank(accessToken)){
           return accessToken;
       } else{
           String redirectUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ WxConstant.appId+"&secret="+WxConstant.appSecret+"";
           try {
               String json2 = null;
               json2 = OkHttpUtil.get(redirectUrl);
               LogKit.info("获取accessToken-------------"+json2);
               JSONObject jsonObject = JSONObject.parseObject(json2);
               String token = jsonObject.getString("access_token");
               CacheKit.put(WxConstant.wxCache, WxConstant.jsapiAccessTokenCache, token);
                   return token;
           } catch (Exception e) {
           LogKit.error(e.getMessage(),e);
               return null;
           }
       }
    }

    /**
     * 获取jsAPititke并缓存
     * @return
     */
    public String getTicket() {
        String ticketCache = CacheKit.get(WxConstant.wxCache,WxConstant.ticketCache);

        if(StringUtils.isNotBlank(ticketCache)){
            return ticketCache;
        }else{
            String url2 = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" +getJsApiAccessToken()+ "&type=jsapi";
            try {

                String json2 = OkHttpUtil.get(url2);
                LogKit.info("getTicket-------------"+json2);
                JSONObject jsonObject = JSONObject.parseObject(json2);
                String ticket = jsonObject.getString("ticket");
                if(StringUtils.isNotBlank(ticket)) {
                    CacheKit.put(WxConstant.wxCache, WxConstant.ticketCache, ticket);
                    return ticket;
                }else{
                    return null;
                }
            } catch (Exception e) {
                LogKit.error(e.getMessage(),e);
                return null;
            }
        }
    }

    public ApiRespData<WxJsapiResp> jsApi(ApiReqData<WxJsapiReq> apiReqData ){
        WxJsapiResp wxJsapiResp = new WxJsapiResp();
        WxJsapiReq wxJsapiReq =apiReqData.getBody();
        String url =apiReqData.getHead().getHttpServletRequest().getRequestURL().toString();
        if(wxJsapiReq!=null&&StringUtils.isNotBlank(wxJsapiReq.getUrl())){
            url = wxJsapiReq.getUrl();
        }
        try {
            url = URLDecoder.decode(url, "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String ticket = getTicket();
        if(ticket!=null) {
            JSONObject map = Sign.sign(ticket, url);
            if (map != null) {
                wxJsapiResp.setAppId(PropKit.use("three-app.properties").get("wx.appid"));
                wxJsapiResp.setJsapiTicket(map.getString("jsapi_ticket"));
                wxJsapiResp.setUrl(map.getString("url"));
                wxJsapiResp.setNonceStr(map.getString("nonceStr"));
                wxJsapiResp.setTimestamp(map.getString("timestamp"));
                wxJsapiResp.setSignature(map.getString("signature"));
                return ApiRespData.buildSucc(wxJsapiResp);
            } else {
                return ApiRespData.buildFail();
            }
        }
        return ApiRespData.buildFail();
    }
}
